import pygame
from pygame.sprite import Group
from bullet import Bullet


class Ship:
    def __init__(self, screen, img_path, speed_factor = 1):
        self.screen = screen
        self.img = pygame.image.load(img_path)
        self.rect = self.img.get_rect()
        self.screen_rect = self.screen.get_rect()

        self.speed_factor = speed_factor
        self.cx = float(self.screen_rect.centerx)
        self.cy = float(self.screen_rect.bottom)

        self.rect.centerx = self.cx
        self.rect.centery = self.cy

        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

        self.bullets = Group()

    def blit_actor(self):
        self.screen.blit(self.img, self.rect)

    def check_ev(self, ev):
        if ev.type == pygame.KEYDOWN:
            self.check_ev_keydown(ev)
        elif ev.type == pygame.KEYUP:
            self.check_ev_keyup(ev)

    def check_ev_keydown(self, ev):
        if ev.key == pygame.K_LEFT:
            self.moving_left = True
        elif ev.key == pygame.K_RIGHT:
            self.moving_right = True
        elif ev.key == pygame.K_UP:
            self.moving_up = True
        elif ev.key == pygame.K_DOWN:
            self.moving_down = True
        elif ev.key == pygame.K_SPACE:
            new_bullet = Bullet(self.screen, self.rect.centerx, self.rect.centery)
            self.bullets.add(new_bullet)

    def check_ev_keyup(self, ev):
        if ev.key == pygame.K_LEFT:
            self.moving_left = False
        elif ev.key == pygame.K_RIGHT:
            self.moving_right = False
        elif ev.key == pygame.K_UP:
            self.moving_up = False
        elif ev.key == pygame.K_DOWN:
            self.moving_down = False

    def moving_update(self):
        for bullet in self.bullets.sprites():
            bullet.moving_update()
            if bullet.rect.bottom < 0:
                self.bullets.remove(bullet)
        if self.moving_left and self.rect.left > self.screen_rect.left:
            self.cx -= self.speed_factor
            self.rect.centerx = self.cx
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.cx += self.speed_factor
            self.rect.centerx = self.cx
        if self.moving_up and self.rect.top > self.screen_rect.top:
            self.cy -= self.speed_factor
            self.rect.centery = self.cy
        if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
            self.cy += self.speed_factor
            self.rect.centery = self.cy
        self.blit_actor()
